package day_02_ThreadCommunicate;

/**
 * 资源类--我自己的方式实现的线程交替操作
 */
class MyResource{

    private int number = 0;

    public synchronized void increment() {
        System.out.print(Thread.currentThread().getName() + "\t" + number);
        if(number==0){
            number++;
        }
        System.out.println("\t-->\t" + number);
        this.notifyAll();
        try {
            this.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.notifyAll();
    }

    public synchronized void decrement() {
        System.out.print(Thread.currentThread().getName() + "\t" + number);
        if(number==1){
            number--;
        }
        System.out.println("\t-->\t" + number);
        this.notifyAll();
        try {
            this.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.notifyAll();
    }

}

/**
 * @Description 线程间通信--两个线程交替操作资源类【方式一：我自己的方式实现线程交互操作】
 * @Author shihan
 * @Date 2020/10/25 16:20
 * @Version 1.0
 */
public class ThreadWaitNotifyDemo {

    /**
     * 实现两个线程交替操作：
     * 线程A将数 +1，线程B将数 -1，交替执行10轮
     * @param args
     */
    public static void main(String[] args) {
        MyResource myResource = new MyResource();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                myResource.increment();
            }
        },"线程A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                myResource.decrement();
            }
        },"线程B").start();
    }
}
